import json
import time
from wxauto import WeChat

wx = WeChat()

env_config = json.load(open('env.config.json', 'r'))

msgkeyword = f"@{env_config['robot_username']}"

class WxMsgWatcher:

    def new_msgs(self):
        while 1:
            time.sleep(3)
            for group_name, user_msgs in wx.GetAllNewMessage().items():
                for user_name, msg, msg_time in user_msgs:
                    # 只要收到的消息中有@机器人，就接收
                    if msgkeyword not in msg:
                        continue
                    msg = msg.replace(msgkeyword, '').strip()
                    yield {
                        'group_name': group_name,
                        'from_user': user_name,
                        'msg': msg,
                        'msg_time': msg_time
                    }
    def get_who_and_msg(self, msg, group_name, user_name):
        who = None
        if msg.startswith('@'):
            who = msg.split()[0][1:]
            msg = msg.replace(f'@{who} ', '')
        return who, msg

    def send_msg(self, msg, group_name, user_name):
        who, msg = self.get_who_and_msg(msg, group_name, user_name)
        wx.SendMsg(msg, who)

    def send_img(self, group_name, user_name, img_path):
        who, msg = self.get_who_and_msg('', group_name, user_name)
        wx.SendFiles(img_path, who)


def test_get_new_msgs():
    watcher = WxMsgWatcher()
    for msg in watcher.new_msgs():
        print(json.dumps(msg, ensure_ascii=False))


def test_send_msg():
    watcher = WxMsgWatcher()
    watcher.send_msg('hello', None, user_name='测试用户')


if __name__ == '__main__':
    # test_get_new_msgs()

    watcher = WxMsgWatcher()
    watcher.send_msg('hello', 'KTT找货助手', None)